package org.itboys.shop.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.itboys.baseobject.entity.City;
import org.itboys.baseobject.service.CityService;
import org.itboys.basetemplate.entity.Favorite;
import org.itboys.basetemplate.service.FavoriteService;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.member.entity.Member;
import org.itboys.product.entity.Product;
import org.itboys.product.service.ProductService;
import org.itboys.shop.entity.ShopSeller;
import org.itboys.shop.service.ScenicSpotService;
import org.itboys.shop.service.ShopSellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 游记
 */
@RestController
@RequestMapping(value = "/wx/collection")
public class WXCollectionController extends BaseController{

	@Autowired
	private ShopSellerService sellerService;
	@Autowired 
	private ProductService productService;
	@Autowired
	private FavoriteService favoriteService;
	@Autowired
	private CityService cityService;
	@Autowired
	private ResourceHolder resourceHolder;
	@Autowired
	private ScenicSpotService scenicSpotService;
	/**
	 * 收藏
	 * @param type PRODUCCT("普通商品",1),HOTEL("民宿",2),BASE("基地", 3),SENIC("景点", 4),FRAM_STAY("农家乐", 5)
	 * @param objId
	 * @param response
	 */
	@RequestMapping("/add")
	public void save( @RequestParam Long objId, @RequestParam(value="type") Integer type,
			 HttpServletRequest request, HttpServletResponse response) {
		try {
			Member member = (Member) request.getSession().getAttribute("user");
			Long memberId = member.getId();
			String msg = "收藏成功！";
			int code = 0;
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("memberId", memberId);
			map.put("objId", objId);
			map.put("type", type);
			List<Favorite> list = favoriteService.list(map);
			if(list.size() > 0) {
				Integer status = list.get(0).getIsDeleted();
				if (status!=null && status==1) {
					list.get(0).setIsDeleted(0);
				}else{
					list.get(0).setIsDeleted(1);
					msg = "取消收藏成功！";
					code = 1;
				}
				favoriteService.update(list.get(0));
			} else {
				Favorite favorite = new Favorite();
				favorite.setObjId(objId);
				favorite.setType(type);
				favorite.setCreateTime(new Date());
				favorite.setMemberId(memberId);
				favorite.setIsDeleted(0);
				favoriteService.save(favorite);
			}
			AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgCodeResultDO(code, msg));
		} catch (Exception e) {
			logger.error("add error", e);
			AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "系统异常!"));
		}
	}
	/**
	 * 列表页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/toList")
	public ModelAndView toList(Integer page, Integer rows, Integer type, Model model){
		if (page == null) {
			page = 1;
		}
		if (rows == null) {
			rows = 10;
		}
		if (type == null) {
			type = 1;
		}
		model.addAttribute("page", page);
		model.addAttribute("rows", rows);
		model.addAttribute("type", type);
		addAttribute(model);
		return new ModelAndView("member/myCollection");
	}
	/**
	 * 分页查询
	 * @param type PRODUCCT("普通商品",1),HOTEL("民宿",2),BASE("基地", 3),SENIC("景点", 4),FRAM_STAY("农家乐", 5)
	 * @param request
	 * @param response
	 */
	@RequestMapping("/list")
	public void list(Integer type, Integer page, Integer rows, HttpServletRequest request,HttpServletResponse response){
		Member member = (Member) request.getSession().getAttribute("user");
		Long memberId = member.getId();
		Map<String, Object> param = new HashMap<String,Object>();
		param.put("type", type);
		param.put("memberId", memberId);
		param.put("isDeleted", 0);
		param.put("pageNo", page);
		param.put("pageSize", rows);
		param.put("orderByKey", "-createTime");
		String imgRoot = resourceHolder.getStringValue("imgRoot");
		List<Favorite> list = favoriteService.listWithPaging(param);
		List<Long> ids = new ArrayList<Long>();
		for (Favorite bean : list) {
			if (bean!=null) {
				ids.add(bean.getObjId());
			}
		}
		param.clear();
		param.put("id in", ids);
		switch (type) {
		case 1:
			List<Product> products = productService.list(param);
			List<Long> sourceIds = new ArrayList<Long>();
			for (Product product : products) {
				sourceIds.add(product.getSource());
			}
			param.clear();
			param.put("id in", sourceIds);
			List<City> cities = cityService.list(param);
			for (City bean : cities) {
				for (Product product : products) {
					if (bean.getId()==product.getSource()) {
						product.setScheduleDesc(bean.getName());
					}
				}
			}
			for (Product product : products) {
				for (Favorite bean : list) {
					if (bean.getObjId()==product.getId()) {
						bean.setName(product.getName());
						if (product.getImage()!=null && !"".equals(bean.getImage())) {
//							bean.setImage(imgRoot+product.getImage());
							bean.setImage(product.getImage());
						}
						bean.setPrice(product.getPrice()/100);
						bean.setSource(product.getScheduleDesc());
					}
				}
			}
			break;
		case 2:
			List<ShopSeller> msSellers = sellerService.list(param);
			for (ShopSeller seller : msSellers) {
				for (Favorite bean : list) {
					if (bean.getObjId()==seller.getId()) {
						bean.setName(seller.getName());
						if (seller.getLogo()!=null && !"".equals(seller.getLogo())) {
							bean.setImage(imgRoot+seller.getLogo());
//							bean.setImage(seller.getLogo());
						}
						//bean.setPrice();
					}
				}
			}
			break;
		case 4:
//			List<ScenicSpot> spots = scenicSpotService.list(param);
//			for (ScenicSpot spot : spots) {
//				for (Favorite bean : list) {
//					if (bean.getObjId()==spot.getId()) {
//						bean.setName(spot.getName());
//						if (spot.getMainImg()!=null && !"".equals(spot.getMainImg())) {
//							bean.setImage(imgRoot+spot.getMainImg());
//						}
//						//bean.setPrice();
//					}
//				}
//			}
			List<ShopSeller> jdSellers = sellerService.list(param);
			for (ShopSeller seller : jdSellers) {
				for (Favorite bean : list) {
					if (bean.getObjId()==seller.getId()) {
						bean.setName(seller.getName());
						if (seller.getLogo()!=null && !"".equals(seller.getLogo())) {
							bean.setImage(imgRoot+seller.getLogo());
//							bean.setImage(seller.getLogo());
						}
						//bean.setPrice();
					}
				}
			}
			break;
		case 5:
			List<ShopSeller> njlSellers = sellerService.list(param);
			for (ShopSeller seller : njlSellers) {
				for (Favorite bean : list) {
					if (bean.getObjId()==seller.getId()) {
						bean.setName(seller.getName());
						if (seller.getLogo()!=null && !"".equals(seller.getLogo())) {
							bean.setImage(imgRoot+seller.getLogo());
//							bean.setImage(seller.getLogo());
						}
						//bean.setPrice();
					}
				}
			}
			break;
		default:
			break;
		}
		JsonPageUtils.renderJsonPage(0L, list, response);
	}
	/**
	 * 异步删除
	 */
	@RequestMapping("/remove")
	public void remove(String id, HttpServletResponse response){
		try {
			if (id!=null && !"".equals(id)) {
				String ids[] = id.split(",");
				for (String str : ids) {
					favoriteService.update(Long.parseLong(str), "isDeleted", new Integer(1));
				}
			}
			AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(null, "操作成功!"));
		} catch (Exception e) {
			logger.error("remove error", e);
			AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "系统异常!"));
		}
	}
	
	/**
	 * 收藏
	 * @param proId
	 * @param request
	 * @param response
	 */
	@RequestMapping("/doCollect")
	public void doCollect(@RequestParam Long proId,HttpServletRequest request,HttpServletResponse response){
		
		Product product=productService.getById(proId);
		
		favoriteService.collect(request, response, proId, product.getProductType());
	}
}
